package de.velvettear.squirrel.executors;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import de.velvettear.squirrel.kernel.File;
import de.velvettear.squirrel.kernel.Statics;
import de.velvettear.squirrel.util.CameraHelper;
import de.velvettear.squirrel.util.FTPHelper;
import de.velvettear.squirrel.util.MySQLHelper;
import de.velvettear.squirrel.util.TimeHelper;

	public class SecurityCamExecutor {

	private static ScheduledExecutorService scheduler;
	private static String cameraMode;
	private static String articleTitle;
	private static ImageView iv;
	private static Context context;
	
	public static void startTakingPictures(Context c, int delay, String mode) {
		startTakingPictures(context, delay, mode, null, null);
	}
	
	public static void startTakingPictures(Context c, int delay, String mode, String title, ImageView view) {		
		cameraMode = mode;
		articleTitle = title;
		iv = view;
		context = c;
		
		if (scheduler == null) {
			scheduler = Executors.newScheduledThreadPool(1);
		}
						
		scheduler.scheduleAtFixedRate(new Runnable() {

			@Override
			public void run() {
				String command = "";
				if (cameraMode.equals(Statics.SECURITYCAM_MODE_LOCAL)) {
					command = Statics.COMMAND_SECURITYCAM_LOCAL;
				} else if (cameraMode.equals(Statics.SECURITYCAM_MODE_FTP)) {
					command = Statics.COMMAND_SECURITYCAM_FTP;
				}
				CameraHelper.takeBackPicture(context, picturesHandler, command);				
			}
			
		}, 0, delay, TimeUnit.SECONDS);
	}
	
	public static void stopTakingPictures() {
		if (scheduler != null) {
			if (!scheduler.isShutdown()) {
				scheduler.shutdown();
			}
			if (!scheduler.isTerminated()) {
				scheduler.shutdownNow();
			}
			scheduler = null;
		}
	}
	
	private static void setPicture(File picture) {
		if (iv != null) {
			Bitmap bmp = BitmapFactory.decodeFile(picture.m_sFullPath);
			iv.setImageBitmap(bmp);
		}
 	}
	
	public static Handler picturesHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Bundle data = msg.getData();
			String command = data.getString(Statics.MESSAGE_PICTURE_COMMAND);			
			
			if (command.equals(Statics.COMMAND_SECURITYCAM_LOCAL)) {
				
			} else if (command.equals(Statics.COMMAND_SECURITYCAM_FTP)) {
				File picture = new File(data.getString(Statics.MESSAGE_PICTURE_PATH));
				FTPHelper.uploadFile(picture, "/VelvetTear/SecurityCam", "image.jpg", true);
				
				if (articleTitle != null) {
					MySQLHelper.updateSecurityCamArticle(articleTitle, TimeHelper.formatFileDate(picture));
				}
				
				setPicture(picture);				
			}
		}
	};
	
}
